<html>
<head>
    <title>BugMeNot</title>
    <link rel="Stylesheet" href="style.css" />

    <script type="text/javascript" src="mootools.js"></script>

    <script type="text/javascript">
        window.addEvent('domready', function()
        {
            var mainBlock = $('mainBlock');
            chrome.tabs.getSelected(null, getSelectedTab.bind(this));
            // DEBUG MODE
            //getSelectedTab({ url: 'http://www.nytimes.com/' });

            function getSelectedTab(tab)
            {
                var matchLocation = tab.url.match(/\/\/([^\/]+)\//);
                var currDomain = '';
                //debugger;
                if (!matchLocation || tab.url.test('^chrome', 'i'))
                {
                    //will happen with about:config, about:blank,...
                    NoResults();
                    currDomain = tab.url;
                    return;
                }

                SendTabCommand('BMN_CatchLoginForm', null);

                currDomain = matchLocation[1];
                var req = new XMLHttpRequest();
                var getUrl = 'http://www.bugmenot.com/view/' + currDomain + '?utm_source=extension&utm_medium=firefox';
                req.open("GET", getUrl, true);
                req.onload = parseAccunts;
                (function() { this.send(null); }).bind(req).delay(500);
            }

            function parseAccunts()
            {
                if (this.status != 200)
                {
                    return NoResults(mainBlock);
                }

                var accountList = processBugMeNotResponse(this.responseText);
                if (accountList.snapshotLength > 0)
                {
                    removeLoadingBlock();
                    for (var i = 0; i < accountList.snapshotLength; i++)
                    {
                        var account = accountTableInfo(accountList, i, /username|password|stats|other/);
                        addNewAccount(account);
                        account = null;
                    }
                }
                else
                {
                    NoResults(mainBlock);
                }
                accountList = null;
            };

            function closeThisWindow()
            {
                window.close();
                chrome.experimental.extension.getPopupView().close();
            };

            function removeLoadingBlock()
            {
                var loading = $('loading');
                if (!loading) return;
                loading.parentNode.removeChild(loading);
            };

            function NoResults()
            {
                removeLoadingBlock();
                var noRes = new Element('div', { id: 'loading', 'class': 'loading' }).set('html', '<b>No results</b>').inject(mainBlock);
            };

            function addNewAccount(account)
            {
                if (!mainBlock) return;
                var divAccount = new Element('div', { 'class': 'account' }).inject(mainBlock);

                new Element('div', { 'class': 'title' }).set('html', 'Username').inject(divAccount);
                new Element('div', { 'class': 'val' }).set('html', account.username).inject(divAccount);
                new Element('div', { 'class': 'title' }).set('html', 'Password').inject(divAccount);
                new Element('div', { 'class': 'val' }).set('html', account.password).inject(divAccount);

                var moreBlock = new Element('div', { 'class': 'moreBlock', 'style': 'display:none;' }).inject(divAccount);
                new Element('div', { 'class': 'title' }).set('html', 'Other').inject(moreBlock);
                new Element('div', { 'class': 'val' }).set('html', account.other).inject(moreBlock);
                //<div class="title">Stats</div><div class="val stats"><em class="good">84% success rate</em> (266 votes)</div>'
                new Element('div', { 'class': 'title' }).set('html', 'Stats').inject(moreBlock);
                new Element('div', { 'class': 'val stats' }).set('html', account.stats).inject(moreBlock);

                new Element('div', { 'class': 'vote' }).inject(moreBlock)
                    .grab(new Element('lable').set('html', 'Did this login work out for you?'))
                    .grab(new Element('input', { 'type': 'submit', 'value': 'Yes', 'class': 'submit yes', 'title': 'No Implemented Yet' }).addEvent('click', function(e) { e.stop(); } .bind(this)))
                    .grab(new Element('input', { 'type': 'submit', 'value': 'No', 'class': 'submit no', 'title': 'No Implemented Yet' }).addEvent('click', function(e) { e.stop(); } .bind(this)));

                new Element('div', { 'class': 'loginBtn' })
                    .set('html', '<img src="icon.png" width="24" height="24" alt="login button" />').inject(divAccount)
                    .addEvent('click', function(e)
                    {
                        e.stop();
                        SendTabCommand('BMN_DoSubmit', this, function() { closeThisWindow(); });
                    } .bind(account));

                var moreBtn = new Element('div', { 'class': 'moreBtn down' }).inject(divAccount)
                    .addEvent('click', function(e, block)
                    {
                        e.stop();
                        this.setStyle('display', this.getStyle('display') == 'none' ? 'block' : 'none');
                        e.target.toggleClass('down').toggleClass('up');
                    } .bind(moreBlock));

                divAccount = null;
            };

            function SendTabCommand(command, args, afertSend)
            {
                chrome.tabs.getSelected(null, function(tab)
                {
                    chrome.tabs.sendRequest(tab.id, { command: command, args: args });
                    if (afertSend && $type(afertSend) == 'function')
                    {
                        afertSend.run();
                    }
                });
            };

            function accountTableInfo(accountList, accountNumber, matchExpression)
            {
                var element = accountList.snapshotItem(accountNumber);
                var childElementList = element.getElementsByTagName('tr');
                var accountInfo = new Object();
                for (var i = 0; i < childElementList.length; i++)
                {
                    var rowHeading = childElementList[i].getElementsByTagName('th')[0].textContent.trim().toLowerCase();
                    if (rowHeading.match(matchExpression))
                    {
                        accountInfo[rowHeading] = childElementList[i].getElementsByTagName('td')[0].textContent.trim();
                    }
                }
                return accountInfo;
            };

            function processBugMeNotResponse(responseText)
            {
                //debugger;
                var loginFormFound = true;
                var xmlString = "<?xml version=\"1.0\"?>\n" + responseText;
                var domParser = new DOMParser();
                var response = domParser.parseFromString(xmlString, 'text/xml');
                var xpe = new XPathEvaluator();
                return xpe.evaluate('//*[@class="account"]|//*[@class="account valid"]', response, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
            };

        });
    </script>

</head>
<body class="view">
    <div class="document">
        <div id="mainBlock" class="panel minor">
            <h2>
                Account Details</h2>
            <div id="loading" class="loading">
                <img src="ajax-loader.gif" align="middle" alt="loading" />
            </div>
        </div>
    </div>
</body>
</html>
